package org.example.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.WebSocket;
import org.example.commonapi.domain.Personality;
import org.example.commonapi.domain.Practice;
import org.example.commonapi.domain.PracticeHistory;
import org.example.commonapi.domain.R;
import org.example.commonapi.domain.RecommendWord;
import org.example.commonapi.domain.User;
import org.example.commonapi.domain.Video;
import org.example.commonapi.domain.VideoHistory;
import org.example.commonapi.mapper.PersonalityMapper;
import org.example.commonapi.mapper.PracticeHistoryMapper;
import org.example.commonapi.mapper.PracticeMapper;
import org.example.commonapi.mapper.UserMapper;
import org.example.commonapi.mapper.VideoHistoryMapper;
import org.example.commonapi.mapper.VideoMapper;
import org.example.commonapi.response.RoleContent;
import org.example.commonapi.response.bigmodel.SparkChatListener;
import org.example.commonapi.util.JwtUtil;
import org.example.commonapi.vo.VideoVO;
import org.example.service.AiRecommendService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

import static java.lang.Math.min;
import static org.example.utils.AuthUtil.getAuthUrl;

@Service
public class AiRecommendServiceImpl implements AiRecommendService {
    @Value("${APP.APPID}")
    public String appId;
    @Value("${APP.APISecret}")
    public String apiSecret;
    @Value("${APP.APIKey}")
    public String apiKey;
    private List<RoleContent> historyList = new ArrayList<>();
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PersonalityMapper personalityMapper;
    @Autowired
    private VideoMapper videoMapper;
    @Autowired
    private VideoHistoryMapper videoHistoryMapper;
    @Autowired
    private PracticeHistoryMapper practiceHistoryMapper;
    @Autowired
    private PracticeMapper practiceMapper;


    @Override
    public R<List<RecommendWord>> aiRecommendWord(String text, String from, String to) {
        JSONArray aiResponse = new JSONArray();
        JSONObject aiRecommendWord = new JSONObject();
        aiRecommendWord.put("word", "");
        aiRecommendWord.put("wordType", "");
        aiRecommendWord.put("wordTranslate", "");
        aiRecommendWord.put("wordExample", "");
        aiResponse.add(aiRecommendWord);
        System.out.println("JSON字符串=>" + aiResponse.toJSONString());
        String question = "我正在使用机器翻译，我翻译的语句/单词是：" + text + "，起始语种：" + from + "，目标语种：" + to + "，现在我需要你帮我推荐3个语种为" + from + "相关单词，并使用" + aiResponse.toJSONString() + "这样的JSON格式给我，JSON串中wordExample代表例句,wordType代表词性，word代表推荐单词，这三个的语言都是" + from + "，wordTranslate代表翻译到目标语种后的意思，使用的语言是" + to + "，记住，你只需要给我JSON串，其他话都不用说，记住不需要你说别的话！";
        String answer = askAiQuestion(question);
        // 转化为json字符串
        JSONArray answerJson = JSON.parseArray(answer);
        List<RecommendWord> recommendWordList = new ArrayList<>();
        for (int i = 0; i < answerJson.size(); i++) {
            JSONObject recommendWordJson = answerJson.getJSONObject(i);
            RecommendWord recommendWord = new RecommendWord();
            recommendWord.setWord(recommendWordJson.getString("word"));
            recommendWord.setWordType(recommendWordJson.getString("wordType"));
            recommendWord.setWordTranslate(recommendWordJson.getString("wordTranslate"));
            recommendWord.setWordExample(recommendWordJson.getString("wordExample"));
            recommendWordList.add(recommendWord);
        }
        return R.success(recommendWordList);
    }

    /**
     * 根据当前视频id获取推荐视频
     * @param videoId
     * @return
     */
    @Override
    public R<List<VideoVO>> getAiRecommendVideo(Integer videoId) {
        // 根据当前videoId获取当前视频
        LambdaQueryWrapper<Video> videoQueryWrapper = new LambdaQueryWrapper<>();
        videoQueryWrapper.eq(Video::getId, videoId);
        Video video = videoMapper.selectOne(videoQueryWrapper);
        String question = "我正在观看" + video.getTitle() + "，它的标签是" + video.getTag() + "，我想让你帮我从数据库中推荐5个相似的视频。数据库中视频如下，你只需要告诉我推荐视频的id并用逗号分隔就可以了，记住，只用说5个id，不要说其他任何话。";
        // 获取全部视频
        List<Video> videoList = videoMapper.selectList(null);
        for (Video existedVideo : videoList) {
            question += "视频id:" + existedVideo.getId() + " 视频标题:" + existedVideo.getTitle() + " 视频标签:" + existedVideo.getTag() + "\n";
        }
        String answer = askAiQuestion(question);
        String[] videoIds = answer.split(",");
        // 转换为Integer
        List<Integer> videoIdList = new ArrayList<>();
        for (String videoIdStr : videoIds) {
            Integer integerVideoId = Integer.parseInt(videoIdStr.trim());
            videoIdList.add(integerVideoId);
        }
        // 查询推荐视频
        LambdaQueryWrapper<Video> videoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        videoLambdaQueryWrapper.in(Video::getId, videoIdList);
        List<Video> recommendVideoList = videoMapper.selectList(videoLambdaQueryWrapper);
        // 构造VOList返回给前端
        List<VideoVO> videoVOList = new ArrayList<>();
        for (Video recommendVideo : recommendVideoList) {
            VideoVO videoVO = new VideoVO();
            BeanUtils.copyProperties(recommendVideo, videoVO);
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getId, recommendVideo.getTeacherId());
            User teacher = userMapper.selectOne(userLambdaQueryWrapper);
            videoVO.setPublisherName(teacher.getUsername());
            videoVOList.add(videoVO);
        }
        return R.success(videoVOList);
    }

    @Override
    public R<List<VideoVO>> getHomeRecommendVideo(String subject) {
        // 获取数据库中所有包含subject字段的数据
        LambdaQueryWrapper<Video> videoQueryWrapper = new LambdaQueryWrapper<>();
        videoQueryWrapper.like(Video::getTag, subject);
        List<Video> videoList = videoMapper.selectList(videoQueryWrapper);
        // 构造提示词询问ai
        StringBuilder question = new StringBuilder("我正在观看 " + subject + " 相关视频，以下是数据库中的视频数据，请为我从数据库中推荐8个该科目的视频，我需要的是id，用逗号分隔，记住，你需要说id，不需要你说别的话，再强调一下，只需要说8个数字id！\n");
        for (Video existedVideo : videoList) {
            question.append("视频id：").append(existedVideo.getId()).append("视频标题：").append(existedVideo.getTitle()).append(" 视频标签:").append(existedVideo.getTag()).append(" 视频播放量:").append(existedVideo.getPlayCount()).append(" 视频收藏数:").append(existedVideo.getCollectCount()).append("\n");
        }
        String answer = askAiQuestion(question.toString());
        // 解析ai的回答，提取视频id
        List<String> videoIds = Arrays.asList(answer.split(","));
        // 查询推荐视频
        LambdaQueryWrapper<Video> videoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        videoLambdaQueryWrapper.in(Video::getId, videoIds);
        List<Video> recommendVideoList = videoMapper.selectList(videoLambdaQueryWrapper);
        // 构造VOList返回给前端
        List<VideoVO> videoVOList = new ArrayList<>();
        for (Video recommendVideo : recommendVideoList) {
            VideoVO videoVO = new VideoVO();
            BeanUtils.copyProperties(recommendVideo, videoVO);
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getId, recommendVideo.getTeacherId());
            User teacher = userMapper.selectOne(userLambdaQueryWrapper);
            videoVO.setPublisherName(teacher.getUsername());
            videoVOList.add(videoVO);
        }
        return R.success(videoVOList);
    }

    @Override
    public R<List<VideoVO>> getAiPersonalityVideo(HttpServletRequest request) {
        Long userId = jwtUtil.parseJwt(request.getHeader("token")).getId();
        // 1.查询用户点击频率最高的5个标签
        LambdaQueryWrapper<Personality> personalityLambdaQueryWrapper = new LambdaQueryWrapper<>();
        personalityLambdaQueryWrapper.eq(Personality::getUserId, userId);
        List<Personality> personalityList = personalityMapper.selectList(personalityLambdaQueryWrapper);
        // 2.查询用户距离现在最近一天观看的视频记录
        LambdaQueryWrapper<VideoHistory> videoHistoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        videoHistoryLambdaQueryWrapper.eq(VideoHistory::getUserId, userId);
        videoHistoryLambdaQueryWrapper.orderByDesc(VideoHistory::getWatchTime);
        List<VideoHistory> videoHistoryList = videoHistoryMapper.selectList(videoHistoryLambdaQueryWrapper);
        List<Video> watchedVideo = new ArrayList<>();
        // 根据观看视频id查询出对应视频
        for (VideoHistory videoHistory : videoHistoryList) {
            LambdaQueryWrapper<Video> videoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            videoLambdaQueryWrapper.eq(Video::getId, videoHistory.getVideoId());
            Video video = videoMapper.selectOne(videoLambdaQueryWrapper);
            watchedVideo.add(video);
        }
        // 3.根据用户点击频率最高的5个标签和最近一天观看的视频记录，构造提示词询问ai
        StringBuilder question = new StringBuilder("根据我点击不同标签的频率及我的观看记录，使用推荐算法帮我从数据库中推荐15个我可能感兴趣的视频，我需要的是数据库视频的id，用逗号分隔，记住，你需要说id，不需要你说别的话，再强调一下，只需要说15个数据库中的id，数据库的数据我最后会告诉你\n");
        for ( int i = 0 ; i < min(5,personalityList.size()) ; i ++ ) {
            question.append("标签：").append(personalityList.get(i).getTag()).append("，点击频率：").append(personalityList.get(i).getClickCount()).append("\n");
        }
        for ( int i = 0 ; i < min(10,watchedVideo.size()) ; i ++ ) {
            question.append("最近一天观看视频id：").append(watchedVideo.get(i).getId()).append("，最近一天观看视频标题：").append(watchedVideo.get(i).getTitle()).append("，最近一天观看视频标签：").append(watchedVideo.get(i).getTag()).append("\n");
        }
        // 4.查询数据库中全部视频
        LambdaQueryWrapper<Video> videoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<Video> videoList = videoMapper.selectList(videoLambdaQueryWrapper);
        question.append("记住，你只需要说使用推荐算法得到的推荐的视频id就行，不需要说别的话\n");
        for (Video video : videoList) {
            question.append("数据库中视频id：").append(video.getId()).append("，数据库中视频标题：").append(video.getTitle()).append("，数据库中视频标签：").append(video.getTag()).append("\n");
        }
        String answer = askAiQuestion(question.toString());
        // 解析ai的回答，提取视频id
        List<String> videoIds = Arrays.asList(answer.split(","));
        // 查询推荐视频
        LambdaQueryWrapper<Video> recommendVideoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        recommendVideoLambdaQueryWrapper.in(Video::getId, videoIds);
        List<Video> recommendVideoList = videoMapper.selectList(recommendVideoLambdaQueryWrapper);
        List<VideoVO> videoVOList = new ArrayList<>();
        // 构造VOList
        for (Video video : recommendVideoList) {
            VideoVO videoVO = new VideoVO();
            BeanUtils.copyProperties(video, videoVO);
            videoVOList.add(videoVO);
        }
        return R.success(videoVOList);
    }

    /**
     * 根据科目查询推荐视频
     * @param subject
     * @return
     */
    @Override
    public R<List<VideoVO>> getAiRecommendTargetSubjectVideo(String subject) {
        LambdaQueryWrapper<Video> queryWrapper = new LambdaQueryWrapper<>();
        // 只要tag这个字段有subject科目就查询出来
        queryWrapper.like(Video::getTag, subject);
        List<Video> videoList = videoMapper.selectList(queryWrapper);
        StringBuilder question = new StringBuilder("请帮我推荐使用推荐算法从数据库中推荐15个" + subject + "科目的视频，我需要的是数据库视频的id，用逗号分隔，记住，你需要说id，不需要你说别的话，再强调一下，只需要说15个数据库中的id，以下是数据库数据\n");
        for (Video video : videoList) {
            question.append("数据库中视频id：").append(video.getId()).append("，数据库中视频标题：").append(video.getTitle()).append("，数据库中视频标签：").append(video.getTag()).append("\n");
        }
        // 询问ai
        String answer = askAiQuestion(question.toString());
        // 解析ai的回答，提取视频id
        List<String> videoIds = Arrays.asList(answer.split(","));
        // 查询推荐视频
        LambdaQueryWrapper<Video> recommendVideoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        recommendVideoLambdaQueryWrapper.in(Video::getId, videoIds);
        List<Video> recommendVideoList = videoMapper.selectList(recommendVideoLambdaQueryWrapper);
        List<VideoVO> videoVOList = new ArrayList<>();
        // 构造VOList
        for (Video video : recommendVideoList) {
            VideoVO videoVO = new VideoVO();
            BeanUtils.copyProperties(video, videoVO);
            videoVOList.add(videoVO);
        }
        return R.success(videoVOList);
    }

    @Override
    public R<String> getAiJudgeAndRecommendBySynthesis(HttpServletRequest request) {
        Long userId = jwtUtil.parseJwt(request.getHeader("token")).getId();
        // 获取用户观看视频情况
        LambdaQueryWrapper<VideoHistory> videoHistoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        videoHistoryLambdaQueryWrapper.eq(VideoHistory::getUserId, userId);
        List<VideoHistory> videoHistoryList = videoHistoryMapper.selectList(videoHistoryLambdaQueryWrapper);
        // 按观看时间 获取最新的前5个视频
        videoHistoryList.sort(Comparator.comparing(VideoHistory::getWatchTime).reversed());
        videoHistoryList = videoHistoryList.subList(0, Math.min(5, videoHistoryList.size()));
        // 获取用户的刷题情况
        LambdaQueryWrapper<PracticeHistory> practiceHistoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        practiceHistoryLambdaQueryWrapper.eq(PracticeHistory::getStudentId, userId);
        List<PracticeHistory> practiceHistories = practiceHistoryMapper.selectList(practiceHistoryLambdaQueryWrapper);
        // 按刷题时间 获取最新的前5个刷题记录
        practiceHistories.sort(Comparator.comparing(PracticeHistory::getCreateTime).reversed());
        practiceHistories = practiceHistories.subList(0, Math.min(5, practiceHistories.size()));
        // todo 课程情况
        // 构造问题
        StringBuilder question = new StringBuilder("我是一名大学生，这是我最近的观看的学习视频的历史记录\n");
        for (VideoHistory videoHistory : videoHistoryList) {
            LambdaQueryWrapper<Video> videoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            videoLambdaQueryWrapper.eq(Video::getId, videoHistory.getVideoId());
            Video video = videoMapper.selectOne(videoLambdaQueryWrapper);
            question.append("视频标题：").append(video.getTitle()).append("，").append("视频标签：").append(video.getTag()).append("\n");
        }
        question.append("这是我最近的刷题记录:");
        for (PracticeHistory practiceHistory : practiceHistories) {
            LambdaQueryWrapper<Practice> practiceLambdaQueryWrapper = new LambdaQueryWrapper<>();
            practiceLambdaQueryWrapper.eq(Practice::getId, practiceHistory.getPracticeId());
            Practice practice = practiceMapper.selectOne(practiceLambdaQueryWrapper);
            question.append("题目名称：").append(practice.getName()).append("，").append("题目所属专业：").append(practice.getSubject()).append("\n");
        }
        question.append("请你根据我的上述两者的综合情况，进行评分，评价，推荐下阶段学习方式及路线，记住！你只需要进行评分，评价，推荐下阶段学习方式及路线，不要输出其他内容");
        return R.success(question.toString());
    }

    @Override
    public R<String> getAiJudgeAndRecommendByVideo(HttpServletRequest request) {
        Long userId = jwtUtil.parseJwt(request.getHeader("token")).getId();
        StringBuilder question = new StringBuilder("我是一名大学生，这是我最近的观看的学习视频的历史记录\n");
        LambdaQueryWrapper<VideoHistory> videoHistoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        videoHistoryLambdaQueryWrapper.eq(VideoHistory::getUserId, userId);
        List<VideoHistory> videoHistoryList = videoHistoryMapper.selectList(videoHistoryLambdaQueryWrapper);
        for (VideoHistory videoHistory : videoHistoryList) {
            LambdaQueryWrapper<Video> videoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            videoLambdaQueryWrapper.eq(Video::getId, videoHistory.getVideoId());
            Video video = videoMapper.selectOne(videoLambdaQueryWrapper);
            question.append("视频标题：").append(video.getTitle()).append("，").append("视频标签：").append(video.getTag()).append("\n");
        }
        question.append("请你根据我的上述刷题情况，帮我总结下这段时间的学习记录，然后再给我一些建议，记住！你只需要回答我的问题，不要输出其他内容");
        return R.success(question.toString());
    }

    @Override
    public R<String> getAiJudgeAndRecommendByPractice(HttpServletRequest request) {
        Long userId = jwtUtil.parseJwt(request.getHeader("token")).getId();
        StringBuilder question = new StringBuilder("我是一名大学生，这是我最近的刷题情况:\n");
        LambdaQueryWrapper<PracticeHistory> practiceHistoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        practiceHistoryLambdaQueryWrapper.eq(PracticeHistory::getStudentId, userId);
        List<PracticeHistory> practiceHistories = practiceHistoryMapper.selectList(practiceHistoryLambdaQueryWrapper);
        for (PracticeHistory practiceHistory : practiceHistories) {
            LambdaQueryWrapper<Practice> practiceLambdaQueryWrapper = new LambdaQueryWrapper<>();
            practiceLambdaQueryWrapper.eq(Practice::getId, practiceHistory.getPracticeId());
            Practice practice = practiceMapper.selectOne(practiceLambdaQueryWrapper);
            question.append("题目名称：").append(practice.getName()).append("，").append("题目所属专业：").append(practice.getSubject()).append("是否作答正确：").append(practiceHistory.getStatus()).append("\n");
        }

        question.append("请你根据我的上述刷题情况，帮我总结下这段时间的学习记录，然后再给我一些建议，记住！你只需要回答我的问题，不要输出其他内容");
        return R.success(question.toString());
    }

    @Override
    public R<String> submitPracticeAnswer(Integer id, String answer, HttpServletRequest request) {
        Long userId = jwtUtil.parseJwt(request.getHeader("token")).getId();
        LambdaQueryWrapper<Practice> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Practice::getId, id);
        Practice practice = practiceMapper.selectOne(lambdaQueryWrapper);
        // 更新题目访问量
        practice.setVisits(practice.getVisits() + 1);
        practiceMapper.update(practice, lambdaQueryWrapper);
        // 获取题目类型 判断是不是客观题
        int isRight = 0;
        String aiAnswer = null;
        if ( practice.getType() != 4 ) {
            String trueAnswer = practice.getAnswer();
            isRight = Objects.equals(answer, trueAnswer) ? 1 : 0;
        }else {
            String question = "假定你是一名老师，我是学生，我正在作答简答题" + practice.getContent() + "，这道题目标准答案是" + practice.getAnswer() + "，我的回答是" + answer + "，请帮我判断我的回答是否正确，并给出你判断的理由及修改意见，记住，你需要先回答是否正确，随后使用逗号隔开，在回答理由。";
            aiAnswer = askAiQuestion(question);
            if (aiAnswer.contains("正确")) {
                isRight = 1;
            }
        }
        // 插入一条做题记录
        PracticeHistory practiceHistory = new PracticeHistory();
        practiceHistory.setAnswer(answer);
        practiceHistory.setStatus(isRight);
        practiceHistory.setCreateTime(LocalDateTime.now());
        practiceHistory.setPracticeId(practice.getId());
        practiceHistory.setStudentId(userId);
        practiceHistoryMapper.insert(practiceHistory);
        if ( aiAnswer != null) {
            return R.success(aiAnswer);
        }
        return R.success(isRight == 1 ? "正确" : "错误");
    }

    @Override
    public R<String> getAiTip(Integer id) {
        Practice practice = practiceMapper.selectById(id);
        String question = "假设你是一名老师，我是一名学生，我正在作答题目" + practice.getContent() + "，我苦思冥想没有想出来，请你给我一些提示，记住，你只需要回答我的问题，不要输出其他内容";
        return R.success(askAiQuestion(question));
    }

    /**
     * 根据教学内容获取视频列表
     *
     * @param chapterTitle
     * @return
     */
    @Override
    public R<List<VideoVO>> getVideoListByTeachContent(String chapterTitle) {
        String question = "我这节课的章节标题为" + chapterTitle +"，我想让你帮我从数据库中推荐5个有关的视频。数据库中视频如下，你只需要告诉我推荐视频的id并用逗号分隔就可以了，记住，只用说5个id，不要说其他任何话。";
        // 获取全部视频
        List<Video> videoList = videoMapper.selectList(null);
        for (Video existedVideo : videoList) {
            question += "视频id:" + existedVideo.getId() + " 视频标题:" + existedVideo.getTitle() + " 视频标签:" + existedVideo.getTag() + "\n";
        }

        // 询问ai
        String answer = askAiQuestion(question.toString());
        // 解析ai的回答，提取视频id
        List<String> videoIds = Arrays.asList(answer.split(","));
        // 查询推荐视频
        LambdaQueryWrapper<Video> recommendVideoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        recommendVideoLambdaQueryWrapper.in(Video::getId, videoIds);
        List<Video> recommendVideoList = videoMapper.selectList(recommendVideoLambdaQueryWrapper);
        List<VideoVO> videoVOList = new ArrayList<>();
        // 构造VOList
        for (Video video : recommendVideoList) {
            VideoVO videoVO = new VideoVO();
            BeanUtils.copyProperties(video, videoVO);
            videoVOList.add(videoVO);
        }
        return R.success(videoVOList);
    }



    private String askAiQuestion(String question) {
        StringBuilder answerCache = new StringBuilder();
        SparkChatListener sparkChatListener;
        try {
            sparkChatListener = getAiAnswer(question, answerCache);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        try {
            while (!sparkChatListener.getWsCloseFlag()) {
                Thread.sleep(100);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return answerCache.toString();
    }

    private SparkChatListener getAiAnswer(String question,StringBuilder answer) throws Exception {
        String hostUrl = "https://spark-api.xf-yun.com/v3.5/chat";
        String authUrl = getAuthUrl(hostUrl, apiKey, apiSecret, "GET");
        OkHttpClient client = new OkHttpClient.Builder().build();
        // 构建聊天请求
        JSONObject chatRequest = buildChatRequest(question);
        // 构建websocket请求
        Request request = new Request.Builder().url(authUrl).build();
        SparkChatListener sparkChatListener = new SparkChatListener(answer,new ArrayList<>());
        // 发起websocket请求
        WebSocket webSocket = client.newWebSocket(request, sparkChatListener);
        if (chatRequest != null) {
            webSocket.send(chatRequest.toJSONString());
        }
        return sparkChatListener;
    }

    private JSONObject buildChatRequest(String question) {
        try {
            JSONObject requestJson = new JSONObject();

            JSONObject header = new JSONObject();
            header.put("app_id", appId);
            header.put("uid", UUID.randomUUID().toString().substring(0, 10));

            JSONObject parameter = new JSONObject();
            JSONObject chat = new JSONObject();

            chat.put("domain", "generalv2");
            chat.put("temperature", 0.5);
            chat.put("max_tokens", 4096);
            parameter.put("chat", chat);

            JSONObject payload = new JSONObject();
            JSONObject message = new JSONObject();
            JSONArray text = new JSONArray();

            RoleContent roleContent = new RoleContent();
            roleContent.setRole("user");
            roleContent.setContent(question);
            roleContent.setContent_type("text");
            text.add(JSON.toJSON(roleContent));
            historyList.add(roleContent);

            message.put("text", text);
            payload.put("message", message);

            requestJson.put("header", header);
            requestJson.put("parameter", parameter);
            requestJson.put("payload", payload);
            System.err.println(requestJson);
            return requestJson;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
